<?php

//Including config.php file (Database Connection file)
include('dbconfig.php');
//Including messages.php file (Error messages file)
include('messages.php');

//class with name page
class Page {

    // Insert Process
    public function mysql_insert_array($table, $data, $exclude = array()) {

        $fields = $values = array();

        if (!is_array($exclude))
            $exclude = array($exclude);

        foreach (array_keys($data) as $key) {
            if (!in_array($key, $exclude)) {
                $fields[] = "`$key`";
                $values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
            }
        }

        $fields = implode(",", $fields);
        $values = implode(",", $values);

        $insert = mysql_query("INSERT INTO `$table` ($fields) VALUES ($values)");
        if ($insert) {
            return true;

            // return array( "mysql_error" => false,
            // "mysql_insert_id" => mysql_insert_id(),
            //"mysql_affected_rows" => mysql_affected_rows(),
            //"mysql_info" => mysql_info()
            // );
        } else {
            return array("mysql_error" => mysql_error());
        }
    }

    // Update Process
    public function mysql_update_array($table, $id, $rowid, $array) {

        //public function editUser($array, $userID) {
        // $edited = 'User Ammended';

        /* Assuming array keys are = to database fileds */
        if (count($array) > 0) {
            foreach ($array as $key => $value) {

                $value = mysql_real_escape_string($value); // this is dedicated to @Jon
                $value = "'$value'";
                $updates[] = "$key = $value";
            }
        }
        $implodeArray = implode(', ', $updates);
        $sql = ("UPDATE $table  SET $implodeArray WHERE $rowid=$id");
        mysql_query($sql) or die(mysql_error());
        return true;
    }

    //delete process
    public function delete($rowid, $table, $chk) {

        for ($i = 0; $i < count($chk); $i++) {
            if ($chk[$i] != "") {
                $strSQL = "DELETE FROM $table ";
                $strSQL .="WHERE $rowid = '" . $chk[$i] . "' ";
                $objQuery = mysql_query($strSQL);
            }
        }


        return true;
    }

    // Delete process
    public function group_delete($rowid, $table, $chk) {

        for ($i = 0; $i < count($chk); $i++) {
            if ($chk[$i] != "") {
                //php code to get the data from groups table 
                $products = mysql_query("select * from products where groupid = '" . $chk[$i] . "' ");
                $products_data = mysql_fetch_array($products);
                if (!$products_data) {
                    $strSQL = "DELETE FROM $table ";
                    $strSQL .="WHERE $rowid = '" . $chk[$i] . "' ";
                    $objQuery = mysql_query($strSQL);
                } else {
                    return false;
                }
            }
        }
        return true;
    }

    //Add combination process
    public function add_combination($table, $id, $c_product_id) {

        $check = mysql_query("SELECT * from $table WHERE productid = '$id' and c_product_id = '$c_product_id'");
        $no_rows = mysql_num_rows($check);
        if ($no_rows == 0) {

            //Adding combination by inserting into database
            $add = mysql_query("INSERT INTO $table (c_product_id, productid)
VALUES ('$c_product_id', '$id')") or die(mysql_error());

            if ($add) {
                return True;
            } else {
                return false;
            }
        }
    }

    // Login process
    public function check_login($emailusername, $password) {
//$password = md5($password);
        $data = mysql_query("SELECT * from users WHERE email = '$emailusername' and password = '$password'") or die(mysql_error());
        $data_user = mysql_fetch_array($data);
        $no_rows = mysql_num_rows($data);
        if ($no_rows == 1) {
            $active = 'true';
            if ($data_user['active'] === $active) {
                $_SESSION['login'] = true;
                $_SESSION['username'] = $data_user['username'];
                $_SESSION['userid'] = $data_user['userid'];
                return TRUE;
            } else {
                $mseg = "your account is not activated.";
                //return $mesg;
            }
        } else {
            return FALSE;
        }
    }

    // Admin Login process
    public function admin_login($emailusername, $password) {
//$password = md5($password);
        $data = mysql_query("SELECT * from admin WHERE email = '$emailusername' and password = '$password'") or die(mysql_error());
        $data_user = mysql_fetch_array($data);
        $no_rows = mysql_num_rows($data);
        if ($no_rows == 1) {
            //$active = 'true';
            //if ($data_user['active'] === $active) {
            $_SESSION['login'] = true;
            $_SESSION['admin_username'] = $data_user['username'];
            $_SESSION['adminid'] = $data_user['userid'];
            return TRUE;
            //} else {
            // $mseg = "your account is not activated.";
            //return $mesg;
            //}
        } else {
            return FALSE;
        }
    }
    
    
        // Admin Login process
    public function change_password($c_password, $n_password) {
       $uid= $_SESSION['userid'];
        $current = mysql_query("SELECT password from users WHERE userid = '$uid'") or die(mysql_error());
        $current_pass = mysql_fetch_array($current);
      if($current_pass['password'] == $c_password) {
         $change_pass=mysql_query("update users SET password = '$n_password' where userid = '$uid'") or die(mysql_error());
         if ($change_pass) {
             return TRUE;
         }
      }
      else {
          return FALSE;
      }
     
    }
    
    

    //Registration process
    public function register_user($name, $email, $password) {
        //$password = md5($password);

        $sql = mysql_query("SELECT userid from users WHERE username = '$name' or email = '$email'");
        $no_rows = mysql_num_rows($sql);

        if ($no_rows == 0) {
            $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            $length = 11;

            for ($i = 0; $i < $length; $i++) {
                $ran = rand(0, strlen($alpha) - 1);
                $key .= substr($alpha, $ran, 1);
            }
            //echo $key;
            $active = 'false';
            //REGISTERS USER
            //$result = mysql_real_escape_string(mysql_query("INSERT INTO users(username, email, password, key, active) values ('$name', '$email', '$password', '$key', 'false')")) or die(mysql_error());

            $result = mysql_real_escape_string(mysql_query("INSERT INTO users VALUES('', '$name', '$email', '$password', '$key', '$active')")) or die(mysql_error());

            //SENDS EMAIL THAT TELLS THE USER TO ACTIVATE THE ACCOUNT
            $activation = "login.php?key=" . $key;
            $your_email = 'you'; //CHANGE TO YOUR SETTINGS
            $domain = $_SERVER["HTTP_HOST"]; //YOUR DOMAIN AND EXTENSION
            $directory = dirname($_SERVER["PHP_SELF"]); //FOLDER WHERE THE FILES WILL BE LOCATED
            require_once ('mail1.php');
            $to = $email;
            $subject = "Activate Account";
            $message = "Welcome, " . $name . ". You must activate your account via this message to log in. Click the following link to do so: http://" . $domain . $directory . "/" . $activation;
            $headers = "From: Your Site <" . $your_email . "@" . $domain . ">\r\n"; //MODIFY TO YOUR SETTINGS
            $headers .= "Content-type: text/html\r\n";
            smtpmailer($to, 'chilukurichandu.indian@gmail.com', 'Inventory', 'Activation Mail', $message);

            // if (!empty($error)) echo $error;   

            echo '<script>window.alert("Check ' . $email . ' to activate your account.");</script>';
            return TRUE;
        } else {
            return FALSE;
        }
    }

// Getting session 
    public function get_session() {
        return $_SESSION['username'];
        return $_SESSION['userid'];
    }

    // Getting session 
    public function get_session_admin() {
        return $_SESSION['admin_username'];
        return $_SESSION['adminid'];
    }

    // Logout 
    public function user_logout() {
        $_SESSION['username'] = FALSE;
        //Destroying the session
        session_destroy();
    }

    public function admin_logout() {
        $_SESSION['admin_username'] = FALSE;
        $_SESSION['adminid'] = FALSE;
        //Destroying the session
        session_destroy();
    }

}

?>